#!/bin/bash
### BEGIN INIT INFO
# Provides:          lance_tool
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      1
# Short-Description: Start lance_tool
# Description: Start and Stop the lance_tool
### END INIT INFO
#
# Lance Tool
#
# chkconfig: 345 20 80
# description: Lance Tool
#
# /etc/rc.d/init.d/lance_*
# See how we were called.

PYLX=/root/lancez/applications/xunlei-lixian/lixian_cli.py
DL_LIST=/root/.xunlei.lixian.downloadlist
DL_VOL=/pbfd
DL_DIR=$DL_VOL/incoming
FN_DIR=$DL_VOL/finished
PIDF=/var/run/`basename $0`.pid
LOGF=/root/xunlei.log

function ctime()
{
  date +"%Y/%m/%d %H:%M:%S"
}

touch $DL_LIST

function has_been_downloaded()
{
  taks_id="$1"
  # Check if task was downloaded before
  grep "$task_id" $DL_LIST 1>/dev/null 2>&1
  if [ $? -eq 0 ]
  then
    #echo "[$task_id] `ctime`: Error - Already downloaded !!!" >>$LOGF
    echo "true" && return
  fi
  echo "false" && return
}

function has_enough_space()
{
  task_size="$1"
  # Check if there is enough disk space
  free_1k_blocks=`df | grep "$DL_VOL" | awk '{print $4}'`
  let free_size=free_1k_blocks*1024

  if [ $task_size -gt $free_size ]
  then
    echo "[$task_id] `ctime`: Error - Not enough disk space !!! Download Size=$task_size, Free Space=$free_size" >>$LOGF
    echo "false" && return
  fi
  echo "true" && return
}

function really_download()
{
  task_id="$1"

  echo "[$task_id] `ctime`: Start to download ..." >>$LOGF

  working_dir="$DL_DIR/$task_id"
  [ ! -d $working_dir ] && mkdir -p $working_dir
  cd $working_dir
  no_errors=1

  $PYLX download "$task_id" --continue 1>$working_dir/$task_id.log 2>&1
  [ $? -ne 0 ] && no_errors=0 && \
    echo "[$task_id] `ctime`: Download failed ......" >>$LOGF && return
    
  find ./ | grep ".aria2$"
  [ $? -eq 0 ] && no_errors=0 && \
    echo "[$task_id] `ctime`: Download not finished ......" >>$LOGF && return

  find ./ | grep ".error$"
  [ $? -eq 0 ] && no_errors=0 && \
    echo "[$task_id] `ctime`: Download error occours ......" >>$LOGF && return

  if [ "$no_errors" == "1" ]
  then
    echo $task_id >> $DL_LIST
    cd /
    mv "$working_dir" "$FN_DIR"
    echo "[$task_id] `ctime`: Download completed !" >>$LOGF && return
  fi
  return
}

function download()
{
  task_id="$1"
  task_size="$2"

  [ ! -d "$DL_DIR" ] && mkdir -p "$DL_DIR"
  [ ! -d "$FN_DIR" ] && mkdir -p "$FN_DIR"

  [ `has_been_downloaded "$task_id"` == "true" ] && return
  [ `has_enough_space "$task_size"` == "false" ] && return

  really_download "$task_id"
}

function run_once()
{
  [ -f $PIDF ] && \
    echo "[`ctime`]: Error - Already running, quit!" >>$LOGF && \
    exit 1
  touch $PIDF

  . /etc/profile
  $PYLX list --completed --no-n --id --no-name --size \
  --no-colors --no-status | sort -r | \
  while read fid fdz
  do
    . /etc/profile
    download "$fid" "$fdz"
  done

  rm -f $PIDF
  return
}

function get_pids(){
  ps -elf | grep -v grep | \
  grep "`basename $0`" | grep background | \
  awk '{print $4}' | sort
  return
}

function born_me(){
  get_pids | while read mpid
  do
    echo "`basename $0`-[$mpid] already running!"
    return
  done

  nohup $0 background >/dev/null 2>&1 &
  sleep 1
  get_pids | while read mpid
  do
    echo "`basename $0`-[$mpid] was started ......"
  done
}

function kill_me(){
  get_pids | while read mpid
  do
    kill -s 9 $mpid
    echo "`basename $0`-[$mpid] was stopped!"
  done
  return
}

case "$1" in
  start)
    born_me
    exit 0
  ;;

  stop)
    kill_me
    exit 0
  ;;

  restart)
    $0 stop
    $0 start
    exit 0
  ;;

  status)
    get_pids | while read mpid
    do
      echo "`basename $0`-[$mpid] running ......"
    done
    tail $LOGF -n 1 | awk '{gsub(/\[|\]/,"",$1);print $1}' |\
    while read task_id
    do
      tail -f $DL_DIR/$task_id/$task_id.log
    done
    exit 0
  ;;

  clear)
    rm -f $PIDF
    exit 0
  ;;

  test)
    exit 0
  ;;

  one)
    run_once
    exit 0
  ;;

  background)
    while [ 1 == 1 ]
    do
      run_once
      sleep 600
    done
    exit 0
  ;;

  *)
    echo "Usage: /etc/init.d/`basename $0` {start|stop|restart|status}"
    exit 1
  ;;
esac

